from django.utils.deprecation import MiddlewareMixin
from HomeAutoAI.common.utils.ThreadLocal import *


class SyncTokenMiddleware(MiddlewareMixin):
    def process_request(self, request):
        if request.path in ['/user/token/', '/user/register/', '/llm/audio/test/', '*']:  # 列出所有无需检查的路径
            return
        token = request.headers.get('Authorization')
        if token and token.startswith('Bearer '):
            token = token[7:]
        if token is None:
            raise Exception('Authorization header is missing or invalid')
        set_cur_token(token)

    def process_response(self, request, response):
        set_cur_token(None)
        return response
